<template>
  <div class="validation-rule-editor">
    <div class="editor-header">
      <h3>验证规则配置</h3>
      <div class="header-actions">
        <Button type="primary" @click="saveRule" :loading="saving">
          <IconifyIcon icon="ant-design:save-outlined" />
          保存
        </Button>
        <Button @click="$emit('cancel')">
          <IconifyIcon icon="ant-design:close-outlined" />
          取消
        </Button>
      </div>
    </div>

    <div class="editor-content">
      <Form
        :model="ruleData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        layout="horizontal"
      >
        <!-- 基本信息 -->
        <div class="section">
          <h4>基本信息</h4>
          <FormItem label="规则名称" name="name">
            <Input v-model:value="ruleData.name" placeholder="请输入规则名称" />
          </FormItem>

          <FormItem label="规则描述" name="description">
            <Input.TextArea
              v-model:value="ruleData.description"
              placeholder="请输入规则描述"
              :rows="3"
            />
          </FormItem>

          <FormItem label="是否启用" name="enabled">
            <Switch v-model:checked="ruleData.enabled" />
          </FormItem>
        </div>

        <!-- 验证表达式 -->
        <div class="section">
          <h4>验证表达式</h4>
          <FormItem label="表达式类型" name="type">
            <Select
              v-model:value="ruleData.type"
              placeholder="选择表达式类型"
              @change="onTypeChange"
            >
              <SelectOption value="REGEX">正则表达式</SelectOption>
              <SelectOption value="FUNCTION">自定义函数</SelectOption>
              <SelectOption value="RANGE">数值范围</SelectOption>
              <SelectOption value="LENGTH">长度限制</SelectOption>
              <SelectOption value="FORMAT">格式验证</SelectOption>
            </Select>
          </FormItem>

          <FormItem label="验证表达式" name="expression">
            <Input.TextArea
              v-model:value="ruleData.expression"
              placeholder="请输入验证表达式"
              :rows="4"
            />
          </FormItem>

          <div class="expression-help">
            <h5>表达式说明：</h5>
            <ul>
              <li v-if="ruleData.type === 'REGEX'">
                <strong>正则表达式：</strong>使用JavaScript正则表达式语法
                <br />示例：^[a-zA-Z0-9]+$ (只允许字母和数字)
              </li>
              <li v-if="ruleData.type === 'FUNCTION'">
                <strong>自定义函数：</strong>使用JavaScript函数语法
                <br />示例：function(value) { return value.length > 0; }
              </li>
              <li v-if="ruleData.type === 'RANGE'">
                <strong>数值范围：</strong>使用 min,max 格式 <br />示例：0,100
                (0到100之间)
              </li>
              <li v-if="ruleData.type === 'LENGTH'">
                <strong>长度限制：</strong>使用 min,max 格式 <br />示例：2,50
                (2到50个字符)
              </li>
              <li v-if="ruleData.type === 'FORMAT'">
                <strong>格式验证：</strong>选择预定义格式 <br />支持：email,
                phone, idcard, url等
              </li>
            </ul>
          </div>
        </div>

        <!-- 错误消息 -->
        <div class="section">
          <h4>错误消息</h4>
          <FormItem label="错误消息" name="message">
            <Input
              v-model:value="ruleData.message"
              placeholder="请输入错误提示消息"
            />
          </FormItem>

          <FormItem label="消息模板" name="messageTemplate">
            <Select
              v-model:value="ruleData.messageTemplate"
              placeholder="选择消息模板"
              @change="onMessageTemplateChange"
            >
              <SelectOption value="custom">自定义消息</SelectOption>
              <SelectOption value="field_required">字段必填</SelectOption>
              <SelectOption value="invalid_format">格式不正确</SelectOption>
              <SelectOption value="out_of_range">超出范围</SelectOption>
              <SelectOption value="too_short">长度太短</SelectOption>
              <SelectOption value="too_long">长度太长</SelectOption>
            </Select>
          </FormItem>
        </div>

        <!-- 高级配置 -->
        <div class="section">
          <h4>高级配置</h4>
          <FormItem label="验证时机" name="trigger">
            <Select v-model:value="ruleData.trigger" placeholder="选择验证时机">
              <SelectOption value="onChange">值变化时</SelectOption>
              <SelectOption value="onBlur">失去焦点时</SelectOption>
              <SelectOption value="onSubmit">提交时</SelectOption>
              <SelectOption value="always">实时验证</SelectOption>
            </Select>
          </FormItem>

          <FormItem label="验证级别" name="level">
            <Select v-model:value="ruleData.level" placeholder="选择验证级别">
              <SelectOption value="error">错误</SelectOption>
              <SelectOption value="warning">警告</SelectOption>
              <SelectOption value="info">提示</SelectOption>
            </Select>
          </FormItem>

          <FormItem label="允许空值" name="allowEmpty">
            <Switch v-model:checked="ruleData.allowEmpty" />
          </FormItem>
        </div>
      </Form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import {
  Form,
  FormItem,
  Input,
  Select,
  SelectOption,
  Switch,
  Button,
  message,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
const props = defineProps<{
  rule: any;
  fields: any[];
}>();

// Emits
const emit = defineEmits<{
  update: [rule: any];
  cancel: [];
}>();

// 响应式数据
const saving = ref(false);
const ruleData = reactive({
  id: '',
  name: '',
  description: '',
  enabled: true,
  type: 'REGEX',
  expression: '',
  message: '',
  messageTemplate: 'custom',
  trigger: 'onBlur',
  level: 'error',
  allowEmpty: false,
});

// 监听props变化
watch(
  () => props.rule,
  (newRule) => {
    if (newRule) {
      Object.assign(ruleData, {
        id: newRule.id || '',
        name: newRule.name || '',
        description: newRule.description || '',
        enabled: newRule.enabled !== false,
        type: newRule.type || 'REGEX',
        expression: newRule.expression || '',
        message: newRule.message || '',
        messageTemplate: newRule.messageTemplate || 'custom',
        trigger: newRule.trigger || 'onBlur',
        level: newRule.level || 'error',
        allowEmpty: newRule.allowEmpty || false,
      });
    }
  },
  { immediate: true, deep: true },
);

// 方法
const onTypeChange = (type: string) => {
  // 根据类型设置默认表达式
  switch (type) {
    case 'REGEX':
      ruleData.expression = '^.*$';
      break;
    case 'FUNCTION':
      ruleData.expression = 'function(value) {\n  return true;\n}';
      break;
    case 'RANGE':
      ruleData.expression = '0,100';
      break;
    case 'LENGTH':
      ruleData.expression = '1,50';
      break;
    case 'FORMAT':
      ruleData.expression = 'email';
      break;
  }
};

const onMessageTemplateChange = (template: string) => {
  // 根据模板设置默认消息
  const messages: Record<string, string> = {
    field_required: '此字段为必填项',
    invalid_format: '格式不正确',
    out_of_range: '数值超出范围',
    too_short: '长度太短',
    too_long: '长度太长',
  };

  if (template !== 'custom' && messages[template]) {
    ruleData.message = messages[template];
  }
};

const saveRule = async () => {
  // 验证必填字段
  if (!ruleData.name) {
    message.error('请输入规则名称');
    return;
  }

  if (!ruleData.expression) {
    message.error('请输入验证表达式');
    return;
  }

  if (!ruleData.message) {
    message.error('请输入错误消息');
    return;
  }

  // 验证表达式格式
  if (ruleData.type === 'REGEX') {
    try {
      new RegExp(ruleData.expression);
    } catch (error) {
      message.error('正则表达式格式不正确');
      return;
    }
  }

  if (ruleData.type === 'FUNCTION') {
    try {
      // 简单的函数语法检查
      if (
        !ruleData.expression.includes('function') ||
        !ruleData.expression.includes('return')
      ) {
        message.error('函数表达式格式不正确');
        return;
      }
    } catch (error) {
      message.error('函数表达式格式不正确');
      return;
    }
  }

  saving.value = true;
  try {
    // 模拟保存
    await new Promise((resolve) => setTimeout(resolve, 500));

    const updatedRule = { ...ruleData };
    emit('update', updatedRule);
    message.success('验证规则保存成功');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};
</script>

<style lang="less" scoped>
.validation-rule-editor {
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .editor-content {
    .section {
      margin-bottom: 32px;

      h4 {
        margin: 0 0 16px 0;
        font-size: 14px;
        font-weight: 600;
        color: #333;
        padding-left: 8px;
        border-left: 3px solid #1890ff;
      }
    }

    .expression-help {
      margin-top: 16px;
      padding: 16px;
      background: #f5f5f5;
      border-radius: 6px;

      h5 {
        margin: 0 0 12px 0;
        font-size: 14px;
        font-weight: 600;
        color: #333;
      }

      ul {
        margin: 0;
        padding-left: 20px;

        li {
          margin-bottom: 8px;
          font-size: 13px;
          color: #666;
          line-height: 1.5;

          strong {
            color: #333;
          }
        }
      }
    }
  }
}
</style>
